import {
  VuexModule,
  Module,
  Action,
  Mutation,
  getModule,
} from 'vuex-module-decorators'
import store from '@/store'

export interface IEmailState {
  userId: number
  receivers: any[]
  checkedSenders: number[]
  checkedTemplates: number[]
}

@Module({ dynamic: true, store, name: 'email' })
class Email extends VuexModule implements IEmailState {
  public checkedSenders: number[]
  public checkedTemplates: number[]
  public receivers: any[] = []
  public userId: number = 0

  @Mutation
  public SET_RECEIVERS(receivers: any) {
    this.receivers = receivers
  }

  @Mutation
  public SET_EMAIL_CHECKED_SENDERS(checkedSenders: any) {
    this.checkedSenders = checkedSenders
  }

  @Mutation
  public SET_EMAIL_CHECKED_TEMPLATES(checkedTemplates: any) {
    this.checkedTemplates = checkedTemplates
  }

  @Mutation
  public SET_EMAIL_MODULE(email: any) {
    this.receivers = email?.receivers || []
    this.checkedSenders = email?.checkedSenders || []
    this.checkedTemplates = email?.checkedTemplates || []
    this.userId = email?.userId || 0
  }

  @Action
  public InitEmail(userId: number) {
    const emailStr = localStorage.getItem(`email_${userId}`)
    if (emailStr) {
      const email = JSON.parse(emailStr)
      this.SET_EMAIL_MODULE({ ...email, userId })
    } else {
      this.SET_EMAIL_MODULE({ userId })
    }
  }
}

export const EmailModule = getModule(Email)
